/*
 * @Author: evan.wan
 * @Date:   2016-06-25 15:55:20
 */

'use strict';
define([
    '../../common/service',
    './uploadDialog',
    'text!./tpl/dynamicFilter.html'
], function(
    http,
    UploadDialogView,
    dynamicFilterTpl
) {
    function me() {
        var self = this;
        this.init = function() {
            self.$root = $('.fmp-container');
            self.$filters = self.$root.find('#dynamic-filter');
            self._query = null;
            self.render();
        }

        this.render = function() {
            self.event();
            //列表管理
            $('table[list-manager="templateList"]').listManager('init',{
                supportAdjust:false
                ,supportDrag:false
                ,supportRemind:false
                ,supportConfig:false
                ,setTopVal:135 //调整吸顶的高度,需要减去这个高度
                ,scrollDOM:$('.fmp-article')//监听滚动条
                ,supportSorting	: true
                ,sortUpText		: '-1'
                ,sortDownText	: '1'
                ,sortingCallback: function(query){
                    console.log( query );
                    $.extend(self._query, query);
                    self.getTemplateList();
                }
                ,supportAjaxPage: true
                ,pageCallback:function(query){
                    console.log( query );
                    $.extend(self._query, query);
                    self.getTemplateList();
                }
            }, function(query){
                self.bindDetailPageEvent();
                self.bindEditStatusEvent();
                self.bindDelEvent();
                self._query = query;
                self.getTemplateList();
            });


        }

        this.event = function() {
            //modal打开先请求元素数据
            self.$root.find('#add-template-btn').off('click').on('click', $.proxy(self.openUploadDialog, self));
            self.$root.find('.div-filter').off('click').on('click', $.proxy(self.initFilter, self));
            //search框初始化
            self.initSearch();
            self.filterBtnEvent();

        }

        this.initSearch = function() {
            $(".ndp-search-wrapper[name=templatePlain]").search({
                placeholder: I18N.getText('templateList', 'searchHolder'),
                name:"templateName"
            }).on("do_search",function(e){
                self._query.searchName = self.$root.find('input[name="templateName"]').val() || '';
                self._query.cPage = 1;
                self.getTemplateList();
            });
        }

        /**
         * { 上传模板modal }
         *
         * @method     openUploadDialog
         */
        this.openUploadDialog = function() {
            new UploadDialogView().init(function() {
                self.getTemplateList();
            });
        }

        /**
         * 获取列表数据
         */
        this.getTemplateList = function() {
            var loadingArea = $('.template-table');
            Kit.loading.show(loadingArea);
            http.work('/ectemplate/list',self._query,'POST').then(function(res){
                if (res.succeed){
                    //操作DOM节点更换数据
                    var data = res.data;
                    var _table = $('table[list-manager="templateList"]'),
                        _tbody = $('#template-grid', _table),
                        tmpHtml = '',
                        _list = data.list;

                    if(_list) {
                        for(var i=0; i< _list.length; i++){
                            tmpHtml += self.generateHTML(_list[i]);
                        }
                    }
                    _tbody.html(tmpHtml);
                    _table.listManager([{'resetTd':false, 'resetPageData': data.paginator}]);

                } else {
                    Kit.alert2(res.errorMsg);
                }
                Kit.loading.hide(loadingArea);
            });
        }

        /**
         * 渲染list
         */
        this.generateHTML = function(obj) {
            var timezoneValue = window.sessionStorage.timezoneValue;
            var category = obj.templateName.indexOf('CA') == 0 ? I18N.getText('templateList', 'ca') : I18N.getText('templateList', 'la');
            var tmpHtml = '<tr data-id="'+obj.id+'" data-img="'+obj.templateImg+'" data-name="'+ obj.templateName +'" data-category="'+ category +'">'
                +'<td>' + moment(obj.createTime).utcOffset(timezoneValue).format('YYYY-MM-DD HH:mm') +'</td>'
                +'<td><img class="font-previewimg" src="' + obj.templateImg +'"/></td>'
                +'<td title="'+ obj.templateName +'"><button type="button" class="btn btn-link no-padding go-detail">' +obj.templateName +'</button></td>'
                +'<td>'+ category +'</td>'
                +'<td>'+ ((typeof(obj.groupCnt) === "undefined") ? '':obj.groupCnt) +'</td>'
                +'<td>'+ ((typeof(obj.brandCnt) === "undefined") ? '':obj.brandCnt) +'</td>'
                +'<td><div style="width:50px;float:left;"><span class="switcher" style="position:relative;top:5px;"><label class = "'+(obj.active == 1 ? 'active': '')+'" ><input type = "checkbox" class = "scheckbox" name="checkbox-toggle"></label></span></div>' +
                '<button type="button" title="'+ I18N.getText('templateList', 'templateDelete') +'" class="btn btn-link del-action"><i class="font-icon font-icon-del0" style="font-size: 18px;"></i></button></td>'
                +'</tr>';

            return tmpHtml;
        }

        /**
         * 进入详情页
         */
        this.bindDetailPageEvent = function() {
            $('#template-grid').off('click', '.go-detail');
            $('#template-grid').on('click', '.go-detail', function(){
                var _action = $(this);
                var _tr = _action.closest('tr');
                var _id = _tr.data('id');
                window.localStorage.setItem('goDetailTemplateId', _id);
                window.localStorage.setItem('goDetailTemplateImg', _tr.data('img'));
                window.localStorage.setItem('goDetailTemplateName', _tr.data('name'));
                window.localStorage.setItem('goDetailTemplateCategory', _tr.data('category'));
                window.top.open('#!templateDetail')
            });
        }

        /**
         * 绑定开启 关闭按钮
         */
        this.bindEditStatusEvent = function() {
            var _tbody = $('#template-grid');
            _tbody.off('click', '.switcher');
            _tbody.on('click', '.switcher', function(e){
                var _toggle 	= $(this),
                    _action	= $('input[name="checkbox-toggle"]', _toggle),
                    _tr 		= _action.parents('tr').eq(0),
                    _id 		= _tr.attr('data-id');

                if(_toggle.hasClass('edit-ing')){
                    return false;
                }

                var par = {
                    id: _id,
                    status: _action.parent().hasClass("active") ? 0 : 1
                }
                var _loadIcon = $('<span class="fa fa-refresh refresh-rotation" style="position: relative;margin-left:5px;bottom: 6px;"></span>');
                _toggle.append(_loadIcon);
                //_toggle.addClass('edit-ing');

                http.work('/ectemplate/updateStatus', par,'POST').then(function(res){
                    if (res.succeed){
                        if(res.data.active == 1)
                            _action.parent().addClass("active");
                        else
                            _action.parent().removeClass("active");
                    }
                    else{
                        Kit.alert2(res.errorMsg);
                    }
                    _toggle.removeClass('edit-ing');
                    _loadIcon.fadeOut(300,function(){
                        $(this).remove();
                    });
                });
                return false;
            });
        }

        /**
         * 删除模板
         */
        this.bindDelEvent = function() {
            var delModal= $('#del-modal'),
                confirmAction = $('button[confirm]', delModal);
            delModal.modal({
                backdrop: 'static',
                keyboard: false,
                show: false
            });

            var _batchId,_tr;
            //绑定重试事件
            $('#template-grid').off('click', '.del-action');
            $('#template-grid').on('click', '.del-action', function(){
                var _delAction = $(this);
                _tr = _delAction.closest('tr');
                _batchId = _tr.attr('data-id');
                delModal.modal('show');
            });
            //绑定确定提交事件
            confirmAction.unbind('click');
            confirmAction.bind('click', function(){
                confirmRetry(function(){
                    delModal.modal('hide')
                });
            });
            function confirmRetry(cb){
                var loadingArea = $('.modal-content', delModal);
                Kit.loading.show(loadingArea);
                http.work('/ectemplate/del',_batchId,'POST').then(function(res){
                    if (res.succeed){
                        Kit.alert_success(I18N.getText('templateList', 'templateDeleteSuccess'));
                    }else{
                        Kit.alert2(res.errorMsg);
                    }
                    self.getTemplateList();
                    cb();
                    Kit.loading.hide(loadingArea);
                });
            }
        }

        /**
         * 筛选
         */
        this.initFilter = function() {
            var loadingArea = $('.template-table');
            Kit.loading.show(loadingArea);
            http.work('/ecMaterielCategory/supportTemplateFilter', null,'POST').then(function(res){
                console.info(res)
                if (res.succeed){
                    self.$filters.empty();
                    var structure = '<div class="row" name="creativeTypeRadio"><div class="filter-title">'+ I18N.getText('templateList', 'creativeType') +':</div><div class="filter-body">';
                    structure += '<input id="cus0" class="form-input" type="radio" data-id="0" name="creativeType" checked>';
                    structure += '<label for="cus0"><span class="radio-dot"></span>'+ I18N.getText('templateList', 'all') +'</label>';
                    _.each(res.data, function(el) {
                        structure += '<input id="cus'+ el.id +'" class="form-input" type="radio" data-id="'+ el.id+'" name="creativeType">';
                        structure += '<label for="cus'+ el.id +'" data-id="'+el.id+'"><span class="radio-dot"></span><img src="./imgs/ad-target-'+el.categoryType+'.png" style="height:55px;margin-right:10px;" />'+el.categoryName;
                        structure += '<span class="checkbox-text">[ '+ I18N.getText('templateList', 'detail') +'<span class="sort-down glyphicon glyphicon-chevron-down"></span> ]</span></label>';
                    });
                    structure += '</div></div>';
                    self.$filters.append(structure);

                    var structureDiv = '<div>';
                    _.each(res.data, function(el) {
                        structureDiv += self.initFilterHtml(el);
                    });
                    structureDiv += '</div>';
                    self.$filters.append(structureDiv);

                    $('#search-area').hide();
                    $('.template-table').hide();
                    $('#filter').removeClass("hidden");
                    $('#filter-title-area').removeClass("hidden");

                    $('input[name="creativeType"]').off('click').on('click', function(){
                        if($(this).data('id') == 0) {
                            $('.structure').addClass('hidden');
                        }
                    });

                    $('div[name=creativeTypeRadio] label').off('click').on('click', function() {
                        $('input.filter-checkbox').prop("checked", false);
                        $('input[data-pid='+$(this).data('id')+']').prop("checked", true);
                        $('input[data-pid='+$(this).data('id')+']').parent().parent().removeClass('hidden').siblings().addClass('hidden');
                    });
                }else{
                    Kit.alert2(res.errorMsg);
                }
                Kit.loading.hide(loadingArea);
            });

        }

        /**
         * 动态渲染筛选条件
         */
        this.initFilterHtml = function(el) {
            var tmpHtml = _.template(dynamicFilterTpl)({
                d: el
            });
            return tmpHtml;
        }

        /**
         * 筛选界面 确定 和 取消
         */
        this.filterBtnEvent = function() {
            $('button.btn-filter-ok').click(function() {
                var templateStatus = [],
                    filterList = [];
                $('input[name="templateStatus"]:checked').each(function() {
                    templateStatus.push($(this).val());
                });
                $('#dynamic-filter .row').each(function(x,y){
                    var filterParam = {
                        pid : $(y).data('id')
                    };
                    var ids = [];
                    $(this).find('input[type=checkbox]:checked').each(function(){
                        ids.push($(this).data('id'));
                    });
                    if(ids.length > 0) {
                        filterParam.ids = ids;
                        filterList.push(filterParam);
                    }
                });
                self._query.templateStatus = templateStatus;
                self._query.filterList = filterList;
                self.getTemplateList();
                $('#filter').addClass("hidden");
                $('#filter-title-area').addClass("hidden");
                $('#search-area').show();
                $('.template-table').show();
            });
            $('button[name=cancel]').click(function() {
                $('#filter').addClass("hidden");
                $('#filter-title-area').addClass("hidden");
                $('#search-area').show();
                $('.template-table').show();
            });
        }

        this.getFilterData = function() {
            var tags = [];
            $('input[type=checkbox]:checked').each(function(i, obj) {
                var tag = {
                    id: $(obj).val(),
                    name: $(obj).attr("name"),
                    type: $(obj).attr("data-type"),
                    flag: $(obj).attr("data-flag")
                }
                tags.push(tag);
            });
            return tags;
        }


    }
    return new me();
});
